#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Created on 2019-07-29

@author: zhuyu
"""
import os
import re
import time
import xlwt
import baseFunc


def get_cpu():
    pidr = os.popen("adb shell ps -ef|grep xpaas").readlines()
    pid_r = pidr[0].split(" ")[8]
    li = os.popen("adb shell top -m 100 -n 1 -s 9").readlines()
    name = "com.alipay."
    for line in li:
        if re.findall(name, line):
            cpulist = line.split(" ")
            if cpulist[1].strip() == pid_r:
                # 将list中的空元素删除
                while '' in cpulist:
                    cpulist.remove('')
                # 去掉百分号，返回一个float
                return float(cpulist[8].strip('%'))
    time.sleep(1)


def get_top_cpu():

    li = os.popen("adb shell top -m 20 -n 1 -s cpu").readlines()
    apps_list = {}
    totalcpu = 0
    for i in range(len(li)):
        if i > 4:
            topcpu = li[i].split(" ")
            while '' in topcpu:
                topcpu.remove('')
            if float(topcpu[8].strip('%')) > 0.1 and topcpu[-1].strip('\r').strip('\n') != '9\r':
                if 'top' in topcpu and 'shell'in topcpu:
                    continue
                cpu_value = float(topcpu[8].strip('%'))
                appname = baseFunc.getpackagename(topcpu[0])
                apps_list[appname] = cpu_value
                totalcpu = totalcpu + cpu_value
    print apps_list
    time.sleep(1)
    return totalcpu


def save_cpu(num, info='os'):
    book = xlwt.Workbook(encoding='utf-8')
    # 创建一个名为sheetname的表单
    sheet = book.add_sheet('data')
    j = 0
    sheet.write(j, 0, 'cpu_data')
    try:
        while j < num:
            cpu_data = get_cpu() if info == 'app' else get_top_cpu()
            sheet.write(j+1, 0, cpu_data)
            print cpu_data
            j = j + 1
    finally:
        # 将工作簿以bookname命名并保存
        book.save('{}{}_cpu_{}.xls'.format(baseFunc.MEM_DIRS, info, baseFunc.gettimestr()))


if __name__ == '__main__':
    save_cpu(100)
